package com.cyt.work.association.service.impl;

import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.work.association.dao.WxAssociationSignDao;
import com.cyt.work.association.model.vo.WxAssociationSignVo;
import com.cyt.work.association.dao.WxAssociationNewStuDao;
import com.cyt.work.association.model.po.WxAssociationNewStu;
import com.cyt.work.association.model.vo.WxAssociationNewStuExportVo;
import com.cyt.work.association.model.vo.WxAssociationNewStuVo;
import com.cyt.work.association.model.vo.WxAssociationUserVerifyImportVo;
import com.cyt.work.association.service.WxAssociationNewStuService;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.wx.model.po.WxEducationUser;
import com.cyt.wx.model.vo.WxEducationUserVo;
import com.cyt.wx.service.WxEducationUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * 招新对象关联表-招新对象关联表Service层实现类
 *
 * @author han jun
 * @date 2019-9-3 16:43:32
 */
@Service("wxAssociationNewStuService")
public class WxAssociationNewStuServiceImpl extends BaseServiceImpl<WxAssociationNewStu> implements WxAssociationNewStuService {

    @Resource
    private WxAssociationNewStuDao wxAssociationNewStuDao;

    @Autowired
    private WxEducationUserService wxEducationUserService;

    @Autowired
    private WxAssociationSignDao wxAssociationSignDao;

    @Autowired
    public void setBaseDao(WxAssociationNewStuDao wxAssociationNewStuDao) {
        this.baseDao = wxAssociationNewStuDao;
    }

    /**
     * 分页查询
     *
     * @param wxAssociationNewStuVo 接受参数对象
     * @param pageNum               分页数
     * @param pageSize              每页显示条数
     * @return ReturnResult
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    public ReturnResult findPage(WxAssociationNewStuVo wxAssociationNewStuVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        Example example = new Example(WxAssociationNewStu.class);
        Example.Criteria criteria = example.createCriteria();
        if (StrUtil.isNotEmpty(wxAssociationNewStuVo.getUserNumber())) {
            criteria.andLike("userNumber", "%" + wxAssociationNewStuVo.getUserNumber() + "%");
        }

        if (StrUtil.isNotEmpty(wxAssociationNewStuVo.getUserName())) {
            criteria.andLike("userName", "%" + wxAssociationNewStuVo.getUserName() + "%");
        }
        if (StrUtil.isNotEmpty(wxAssociationNewStuVo.getGradeName())) {
            criteria.andLike("gradeName", "%" + wxAssociationNewStuVo.getGradeName() + "%");
        }

        if (StrUtil.isNotEmpty(wxAssociationNewStuVo.getClassName())) {
            criteria.andLike("className", "%" + wxAssociationNewStuVo.getClassName() + "%");
        }
        //这里是不是做字符串截取的

        if (org.apache.commons.lang3.StringUtils.isNotEmpty(wxAssociationNewStuVo.getAssociationNewId())) {
            criteria.andEqualTo("associationNewId", wxAssociationNewStuVo.getAssociationNewId());
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        List<WxAssociationNewStu> list = wxAssociationNewStuDao.selectByExample(example);
        PageInfo<WxAssociationNewStu> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 分页查询
     *
     * @param wxAssociationNewStuVo 接受参数对象
     * @param pageNum               分页数
     * @param pageSize              每页显示条数
     * @return ReturnResult
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    public ReturnResult findVoPage(WxAssociationNewStuVo wxAssociationNewStuVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
//        PageHelper.orderBy(" create_time desc");
        List<WxAssociationNewStuVo> list = wxAssociationNewStuDao.selectVoList(wxAssociationNewStuVo);
        PageInfo<WxAssociationNewStuVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    @Override
    public ReturnResult findVoHasSignPage(WxAssociationSignVo wxAssociationSignVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<WxAssociationSignVo> list = wxAssociationSignDao.selectVoHasSignList(wxAssociationSignVo);
        PageInfo<WxAssociationSignVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * list查询
     *
     * @param wxAssociationNewStuVo 接受参数对象
     * @return List<WxAssociationNewStu>
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    public List<WxAssociationNewStu> findList(WxAssociationNewStuVo wxAssociationNewStuVo) {
        Example example = new Example(WxAssociationNewStu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        if (StringUtils.isNotEmpty(wxAssociationNewStuVo.getUserNumber())) {
            criteria.andEqualTo("userNumber", wxAssociationNewStuVo.getUserNumber());
        }
        if (StringUtils.isNotEmpty(wxAssociationNewStuVo.getAssociationNewId())) {
            criteria.andEqualTo("associationNewId", wxAssociationNewStuVo.getAssociationNewId());
        }
        return wxAssociationNewStuDao.selectByExample(example);
    }

    /**
     * list查询
     *
     * @param wxAssociationNewStuVo 接受参数对象
     * @return List<WxAssociationNewStu>
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    public List<WxAssociationNewStuVo> findVoList(WxAssociationNewStuVo wxAssociationNewStuVo) {
        return wxAssociationNewStuDao.selectVoList(wxAssociationNewStuVo);
    }

    @Override
    public List<WxAssociationNewStuVo> findVoHasSignList(WxAssociationNewStuVo wxAssociationNewStuVo) {
        return null;
    }

    /**
     * 单个对象查询
     *
     * @param wxAssociationNewStuVo 接受参数对象
     * @return WxAssociationNewStu
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    public WxAssociationNewStu findOne(WxAssociationNewStuVo wxAssociationNewStuVo) {
        WxAssociationNewStu wxAssociationNewStu = new WxAssociationNewStu();
        if (StringUtils.isBlank(wxAssociationNewStuVo.getId())) {
            wxAssociationNewStu.setId(wxAssociationNewStuVo.getId());
        }
        return wxAssociationNewStuDao.selectOne(wxAssociationNewStu);
    }

    /**
     * 单个对象查询
     *
     * @param wxAssociationNewStuVo 接受参数对象
     * @return WxAssociationNewStu
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    public WxAssociationNewStuVo findVoOne(WxAssociationNewStuVo wxAssociationNewStuVo) {
        return wxAssociationNewStuDao.selectVoOne(wxAssociationNewStuVo);
    }

    /**
     * 添加或更新
     *
     * @param wxAssociationNewStuVo 参数接受对象
     * @param sysUser               当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(WxAssociationNewStuVo wxAssociationNewStuVo, SysUser sysUser) {
        if (StringUtils.isBlank(wxAssociationNewStuVo.getId())) {
            WxAssociationNewStu wxAssociationNewStu = new WxAssociationNewStu(sysUser);
            wxAssociationNewStu.setApplyId(wxAssociationNewStuVo.getApplyId());
            wxAssociationNewStu.setAssociationNewId(wxAssociationNewStuVo.getAssociationNewId());
            wxAssociationNewStu.setUserNumber(wxAssociationNewStuVo.getUserNumber());
            wxAssociationNewStu.setUserName(wxAssociationNewStuVo.getUserName());
            wxAssociationNewStu.setClassName(wxAssociationNewStuVo.getClassName());
            wxAssociationNewStu.setGradeName(wxAssociationNewStuVo.getGradeName());
            wxAssociationNewStu.setStatus(wxAssociationNewStuVo.getStatus());
            wxAssociationNewStuDao.insert(wxAssociationNewStu);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            WxAssociationNewStu wxAssociationNewStu = wxAssociationNewStuDao.selectByPrimaryKey(wxAssociationNewStuVo.getId());
            wxAssociationNewStu.setApplyId(wxAssociationNewStuVo.getApplyId());
            wxAssociationNewStu.setAssociationNewId(wxAssociationNewStuVo.getAssociationNewId());
            wxAssociationNewStu.setUserNumber(wxAssociationNewStuVo.getUserNumber());
            wxAssociationNewStu.setUserName(wxAssociationNewStuVo.getUserName());
            wxAssociationNewStu.setClassName(wxAssociationNewStuVo.getClassName());
            wxAssociationNewStu.setGradeName(wxAssociationNewStuVo.getGradeName());
            wxAssociationNewStu.setStatus(wxAssociationNewStuVo.getStatus());
            wxAssociationNewStu.setUpdateTime(new Date());
            wxAssociationNewStu.setUpdateUser(sysUser.getId());
            wxAssociationNewStuDao.updateByPrimaryKey(wxAssociationNewStu);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param wxAssociationNewStuVo 参数接受对象
     * @param sysUser               当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(WxAssociationNewStuVo wxAssociationNewStuVo, SysUser sysUser) {
        //修改字段
        WxAssociationNewStu wxAssociationNewStu = new WxAssociationNewStu();
        wxAssociationNewStu.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        wxAssociationNewStu.setUpdateUser(sysUser.getId());
        wxAssociationNewStu.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(WxAssociationNewStu.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxAssociationNewStuVo.getId())) {
            criteria.andIn("id", Arrays.asList(wxAssociationNewStuVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        wxAssociationNewStuDao.updateByExampleSelective(wxAssociationNewStu, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param wxAssociationNewStuVo 参数接受对象
     * @param sysUser               当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-9-3 16:43:32
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(WxAssociationNewStuVo wxAssociationNewStuVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(WxAssociationNewStu.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxAssociationNewStuVo.getId())) {
            criteria.andIn("id", Arrays.asList(wxAssociationNewStuVo.getId().split(",")));
        }
        if (StringUtils.isNotBlank(wxAssociationNewStuVo.getAssociationNewId())) {
            criteria.andIn("associationNewId", Arrays.asList(wxAssociationNewStuVo.getAssociationNewId().split(",")));
        }
        wxAssociationNewStuDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }


    @Override
    public ReturnResult importExcel(MultipartFile file, SysUser sysUser,String associationNewId,String applyId) {
        // 用户表中是否存在数据
        //移除前面所有的导入的学生
        if (associationNewId==null||associationNewId.length()==0){
            associationNewId = "88888888";
        }else {
        }
        WxAssociationNewStuVo wxAssociationNewStuVo = new WxAssociationNewStuVo();
        wxAssociationNewStuVo.setAssociationNewId(associationNewId);
        List<WxAssociationNewStuVo> deleteAssociation = findVoList(wxAssociationNewStuVo);
        for (WxAssociationNewStuVo wxAssociationNewStuVo1:deleteAssociation){
            remove(wxAssociationNewStuVo1,sysUser);
        }
        ExcelImportResult<WxAssociationUserVerifyImportVo> result = EasyPoiUtil.importExcelResult(file, 1, 1, WxAssociationUserVerifyImportVo.class);
        List<WxAssociationUserVerifyImportVo> questionUserList =  result.getList();
        Map<String, WxAssociationNewStuExportVo> questionUserMap = new HashMap<>();
        String key;
        for (WxAssociationNewStuExportVo questionUser : questionUserList) {
            key = questionUser.getUserNumber();
            if (questionUserMap.keySet().contains(key)) {
                continue;
            }
            questionUserMap.put(key, questionUser);
        }
        List<WxEducationUser> wxEducationUserList = new ArrayList<>();
        List<WxEducationUser> wxEducationUserShow = new ArrayList<>();
        for (Map.Entry<String, WxAssociationNewStuExportVo> entry : questionUserMap.entrySet()) {
            WxAssociationNewStuExportVo userFrom = entry.getValue();
            // 查询账号是否存在
            WxEducationUserVo wxEducationUserVo = new WxEducationUserVo();
            wxEducationUserVo.setUserNumber(userFrom.getUserNumber());
            wxEducationUserVo.setCreateUser(sysUser.getId());
            List<WxEducationUser> list = wxEducationUserService.listExample(wxEducationUserVo);
            if (list != null && list.size() > 0) {
                wxEducationUserShow.addAll(list);
                for (WxEducationUser wxEducationUser:list){
                    if (!wxEducationUser.getName().equals(userFrom.getUserName())){
                        wxEducationUser.setName(userFrom.getUserName());
                        wxEducationUserService.updateByPrimaryKey(wxEducationUser);
                    }
                }
                WxEducationUser wxEducationUser = list.get(0);
                //更新数据库学生的操作
                saveEductionUserList(userFrom,sysUser,wxEducationUser.getId(),associationNewId);
                continue;
            }
            // 账号不存在，保存进用户表
            WxEducationUser wxEducationUser = new WxEducationUser();
            wxEducationUser.setId(BaseUtil.uId());
            wxEducationUser.setApplyId(applyId);
            wxEducationUser.setLoginName(userFrom.getUserNumber());
            wxEducationUser.setMobile(userFrom.getMobile());
            wxEducationUser.setName(userFrom.getUserName());
            wxEducationUser.setUserNumber(userFrom.getUserNumber());
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(userFrom.getMobile()) && userFrom.getMobile().length() == 11) {
                wxEducationUser.setPassword(MD5Util.MD5Encode(StrUtil.sub(userFrom.getMobile(), 5, 11)));
            } else {
                wxEducationUser.setPassword(MD5Util.MD5Encode(BaseConstant.DEFAULT_EDUCATION_USER_PASSWORD));
            }
            wxEducationUser.setUserType("3");
            wxEducationUser.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
            wxEducationUser.setCreateUser(sysUser.getId());
            wxEducationUser.setUpdateUser(sysUser.getId());
            wxEducationUser.setCreateTime(DateUtil.date());
            wxEducationUser.setUpdateTime(DateUtil.date());
            wxEducationUserList.add(wxEducationUser);
            wxEducationUserShow.add(wxEducationUser);
            wxEducationUserService.insert(wxEducationUser);
            saveEductionUserList(userFrom,sysUser,wxEducationUser.getId(),associationNewId);

        }

        if (result.isVerfiyFail()) {
            // 如果错误，打印出提醒，直接返回
            int successNum = 0;
            int failNum = result.getFailList().size();
            if (result.getList() != null && result.getList().size() > 0) {
                successNum = result.getList().size();
            }
            String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
            List<WxAssociationUserVerifyImportVo> failList = result.getFailList();
            // 需要将成功条数也返回
            Map<String, Object> resutlMap = new HashMap<>();
            resutlMap.put("failList", failList);
            resutlMap.put("successList", wxEducationUserShow);
            return new ReturnResult(ErrorCode.CODE_1, resutlMap, errorMsg);
           //return new ReturnResult(wxEducationUserShow);
        }
        int successNumber =0;
        if (result.getList() != null && result.getList().size() > 0) {
             successNumber = result.getList().size();
        }
        String sucess = String.format("共导入%s条，成功%s条，失败0条。", successNumber, successNumber);
        return new ReturnResult(ErrorCode.CODE_0,"" , sucess);
    }

    //新增学生的操作
    private void saveEductionUserList( WxAssociationNewStuExportVo userFrom,SysUser sysUser,String educationUserId, String associationNewId){
        WxAssociationNewStu wxAssociationNewStu = new WxAssociationNewStu();
        wxAssociationNewStu.setId(BaseUtil.uId());
        if (associationNewId==null||associationNewId.length()==0){
            wxAssociationNewStu.setAssociationNewId("88888888");
        }else {
            wxAssociationNewStu.setAssociationNewId(associationNewId);
        }
        wxAssociationNewStu.setGradeName(userFrom.getGradeName());
        wxAssociationNewStu.setClassName(userFrom.getClassName());
        wxAssociationNewStu.setUserName(userFrom.getUserName());
        wxAssociationNewStu.setStatus("3");
        wxAssociationNewStu.setUserNumber(userFrom.getUserNumber());
        wxAssociationNewStu.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
        wxAssociationNewStu.setCreateUser(sysUser.getId());
        wxAssociationNewStu.setUpdateUser(sysUser.getId());
        wxAssociationNewStu.setCreateTime(DateUtil.date());
        wxAssociationNewStu.setUpdateTime(DateUtil.date());
        wxAssociationNewStu.setEducationUserId(educationUserId);
        wxAssociationNewStuDao.insert(wxAssociationNewStu);
    }
}